import enUS from '@/locales/en-US';
import zhCN from '@/locales/zh-CN';
import { getLocale } from '@umijs/max';
import { createIntl } from 'react-intl';

const messagesMap = {
  'zh-CN': zhCN,
  'en-US': enUS,
};

// Default locale
const DEFAULT_LOCALE = 'zh-CN';

// Function to get messages for a given locale
const getMessages = (locale: string) => {
  // @ts-ignore
  return messagesMap[locale] || messagesMap[DEFAULT_LOCALE];
};

// Create a singleton intl instance
let globalIntl: any = null;

// Function to initialize or get the global intl instance
export const getGlobalIntl = () => {
  if (!globalIntl) {
    const locale = getLocale();
    globalIntl = createIntl({
      locale: locale,
      messages: getMessages(locale),
    });
  }
  return globalIntl;
};

// Helper function to format messages
export const formatMessage = (id: string, values?: Record<string, any>) => {
  const intl = getGlobalIntl();
  return intl.formatMessage({ id }, values);
};

// Export a function to manually update the intl instance if needed
export const updateGlobalIntl = () => {
  const locale = getLocale();
  globalIntl = createIntl({
    locale: locale,
    messages: getMessages(locale),
  });
};
